<template>
    <div class="modify">
        <div class="upload">
            <div class="img_upload">
                产品图片:
            </div>
            <div class="images">
                <el-upload v-model:file-list="fileList" :headers="uploadheaders"
                    action="http://111.67.198.176:8111/admin/file/upload/element" list-type="picture-card"
                    :on-success="handleAvatarSuccess">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </div>
        </div>
        <div class="modify_from">
            <el-form ref="ruleFormRef" :model="ruleForm"  label-width="120px" class="demo-ruleForm"
                 status-icon>
                <!-- 产品状态 -->
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="ruleForm.status">
                        <el-radio label="上架" />
                        <el-radio label="下线" />
                    </el-radio-group>
                </el-form-item>
                <!-- 产品分类 -->
                <el-form-item label="产品分类" prop="categoryId">
                    <el-select v-model="ruleForm.categoryId" placeholder="请选择分类">
                        <el-option v-for="(item, i) in category" :key="i" :label="item.categoryName"
                            :value="item.categoryId" />
                    </el-select>
                </el-form-item>
                <!-- 产品分组 -->
                <el-form-item label="产品分组" prop="tagList">
                    <el-select v-model="ruleForm.tagList" multiple placeholder="Select" style="width: 240px">
                        <el-option v-for="(item, i) in ListTagLis" :key="i" :label="item.title" :value="item.id" />
                    </el-select>
                </el-form-item>

                <!-- 产品名称 -->
                <el-form-item label="产品名称">
                    <el-input v-model="ruleForm.prodName" />
                </el-form-item>
                <!-- 产品卖点 -->
                <el-form-item label="产品卖点" prop="brief">
                    <el-input v-model="ruleForm.brief" type="textarea" />
                </el-form-item>
                <!-- 配送方式 -->
                <el-form-item label="配送方式" prop="type">
                    <el-checkbox v-model="ruleForm.deliveryModeVo.hasShopDelivery" label="商家配送" size="large" />
                    <el-checkbox v-model="ruleForm.deliveryModeVo.hasUserPickUp" label="用户自取" size="large" />
                </el-form-item>
                <!-- 运费设置 -->
                <el-form-item v-if="ruleForm.deliveryModeVo.hasShopDelivery" label="运费设置" prop="deliveryTemplateId">
                    <el-select @change="gettransportinfo" v-model="ruleForm.deliveryTemplateId" placeholder="请选择运费设置">
                        <el-option v-for="(item, i) in transportList" :key="i" :label="item.transName"
                            :value="item.transportId" />
                    </el-select>
                    <el-table :data="tableData" style="width: 100%">
                        <el-table-column label="配送区域" width="280">
                            <template #default="{ row }">
                                <div v-if="row.cityList">{{ row.cityList.toString() }}所有区域</div>
                                <div v-else v-for="(item, i) in row.cityList" :key="i">"111"</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="continuousFee" label="首件(个)" width="100" />
                        <el-table-column prop="continuousPiece" label="运费(元)" width="100" />
                        <el-table-column prop="firstFee" label="续件(个)" width="100" />
                        <el-table-column prop="firstPiece" label="续费(元)" width="90" />
                    </el-table>
                </el-form-item>
                <!-- 商品规格 -->
                <el-form-item>
                    <button>添加</button>
                </el-form-item>
                <el-form-item label="商品规格" prop="skuList">
                    <div>
                        <div class="sku" v-for="(item, i) in skuobj" :key="i">
                            <div>{{ i }}</div>
                            <el-tag v-for="tag in item.list" :key="tag" class="mx-1" closable
                                :disable-transitions="false" @close="handleClose(tag, i)">
                                {{ tag }}
                            </el-tag>
                            <el-input v-if="item.flag" ref="InputRef" v-model="inputValue" class="ml-1 w-20"
                                size="small" @keyup.enter="handleInputConfirm(i)" @blur="handleInputConfirm(i)" />
                            <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(i)">
                                +
                            </el-button>
                        </div>
                    </div>
                </el-form-item>
                <!-- sku表格 -->
                <el-form-item label="商品规格" prop="skuList">
                    <avue-crud :option="option" :data="SkuList">
                        <template >
                            <el-upload class="avatar-uploader"
                                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                                :show-file-list="false">
                                <el-icon class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </template>
                        <!-- sku商品名称 -->
                        <template #prodName="{ row }">
                            <el-input v-model="row.prodName" type="textarea" />
                        </template>
                        <!-- sku商品销售价价钱 -->
                        <template #price="row">
                            <el-input-number v-model="row.price" :min="0.01" :max="999" controls-position="right" size="large"/>
                        </template>
                        <!-- sku商品市场价价钱 -->
                        <template #oriPrice="row">
                            <el-input-number v-model="row.oriPrice" :min="0.01" :max="999" controls-position="right" size="large"/>
                        </template>
                        <!-- sku库存 -->
                        <template #stocks="row">
                            <el-input-number v-model="row.stocks" :min="0" :max="999" controls-position="right" size="large"/>
                        </template>
                        <!--sku重量  -->
                        <template #weight="row">
                            <el-input-number v-model="row.weight" :min="0" :max="999" controls-position="right" size="large"/>
                        </template>
                        <!-- sku体积 -->
                        <template #volume="row">
                            <el-input-number v-model="row.volume" :min="0" :max="999" controls-position="right" size="large"/>
                        </template>
                    </avue-crud>
                </el-form-item>


                <!-- <el-form-item label="Instant delivery" prop="delivery">
                    <el-switch v-model="ruleForm.delivery" />
                </el-form-item> -->

                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">Create</el-button>
                    <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script lang="ts" setup>

import { Getmodify, GetCategory, listTagList, transport, transportinfo, speclist, addshop ,putshop} from "../../../api/modify"
import { useRoute ,useRouter} from "vue-router"
import { ref, reactive, nextTick } from "vue"
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile, FormInstance, FormRules, ElInput } from 'element-plus'
const router = useRouter()
const route = useRoute()
// 获取编辑商品的id
const id: any = ref(route.query.id)
// 产品图片列表
const fileList = ref<UploadUserFile[]>([

])
// 获取token
const uploadheaders = ref({
    "Authorization": localStorage.getItem("token")
})

// 获取表单
const ruleFormRef = ref<FormInstance>()
// 图片
const dialogImageUrl = reactive<any>([])
const dialogVisible = ref(false)
// 编辑的表单属性
const ruleForm = reactive<any>({
    brief: "",
    categoryId: "",
    content: "",
    deliveryModeVo: {
        hasShopDelivery: false,
        hasUserPickUp: false,
    },
    deliveryTemplateId: "",
    imgs: "",
    oriPrice: 0.01,
    pic: "",
    price: 0.01,
    prodName: "",
    status: "",
    t: new Date().getTime(),
    tagList: [],
    totalStocks: 0,
})
// 分类列表
let category = reactive<Array<any>>([{}])
// 分组列表
let ListTagLis = reactive<Array<any>>([{}])
// 地址选项 
let transportList = reactive<Array<any>>([{}])
// 地址表格展示
let tableData = reactive<Array<any>>([{}])
// sku表格渲染配置
let option = reactive<any>({
    addBtn: false,
    column: [
    ],
})
// sku列表数据整合
let skuobj = reactive<any>({})
// 商品规格添加绑定value
const inputValue = ref('')
// 提交订单时的sku列表
const SkuList = reactive<Array<any>>([{
    // 折扣前价钱
    oriPrice: 0.01,
    // 折扣后
    price: 0.01,
    // sku商品名称
    prodName: "香甜蛋糕",
    // 
    properties: "",
    // sku名称
    skuName: "",
    // sku状态
    status: 1,
    // 
    stocks: 0,
    // 
    volume: 0,
    // 
    weight: 0,
}])
// 上传图片成功回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    dialogImageUrl.push(URL.createObjectURL(uploadFile.raw!))
    ruleForm.pic =   response
    ruleForm.imgs = response
}

// 处理sku选项整合成规格列表
const Skulist = (list: any) => {
    console.log(list)
    list.forEach((item: any, i: number) => {
        let skuarr = item.properties.split(';')
        skuarr.forEach((it: any, index: any) => {
            let skukey = it.split(':')[0]
            let skuvalue = it.split(":")[1]
            if (!skuobj[skukey]) {
                skuobj[skukey] = {
                    flag: false,
                    list: []
                }
                skuobj[skukey].list.push(skuvalue)
            } else {
                let index = skuobj[skukey].list.indexOf(skuvalue)
                if (index === -1) {
                    skuobj[skukey].list.push(skuvalue)
                }
            }
        })
    })
}
// 添加表格配置项
const Skulistitem = () => {
    option.column = option.column.concat([
        {
            label: "sku图片",
            prop: "pic",
            display: false
        }, {
            label: "商品名称",
            prop: "prodName",
            display: false
        }, {
            label: "销售价",
            prop: "price",
            display: false
        }, {
            label: "市场价",
            prop: "oriPrice",
            display: false
        }, {
            label: "库存",
            prop: "stocks",
            display: false
        }, {
            label: "商品重量(kg)",
            prop: "weight",
            display: false
        }, {
            label: "商品体积(m3)",
            prop: "volume",
            display: false
        }
    ])
}

// 循环商品规格，处理出所有sku列表
const skuIndexListPush = () => {
    for (const key in skuobj) {
        skuobj[key].list.forEach((item: any, i: number) => {
            console.log(item)
        })
    }
}
// 获取编辑信息
const getInfo = async () => {
    let res = await Getmodify(id.value.toString())
    fileList.value.push({
        name: res.data.imgs,
        url: res.data.pic
    })
    ruleForm["prodId"] = res.data.prodId
    ruleForm["version"] = res.data.version
    ruleForm["updateTime"] = res.data.updateTime
    ruleForm["shopId"] = res.data.shopId
    ruleForm["shopName"] = res.data.shopName
    ruleForm.status = res.data.status ? "上架" : "下线",
        ruleForm.tagList = res.data.tagList
    ruleForm.prodName = res.data.prodName
    ruleForm["createTime"] = res.data.createTime
    ruleForm["putawayTime"] = res.data.putawayTime
    ruleForm.brief = res.data.brief
    ruleForm.deliveryTemplateId = res.data.deliveryTemplateId
    ruleForm.deliveryModeVo = JSON.parse(res.data.deliveryMode)
    Skulist(res.data.skuList)
    skuIndexListPush()
}
// 获取分类列表
const getcategory = async () => {
    let res = await GetCategory()
    category = res.data
}
// 获取分组列表
const getListTagList = async () => {
    let res = await listTagList()
    ListTagLis = res.data
}
// 获取地址选项
const gettransport = async () => {
    let res = await transport()
    transportList = res.data
}
// 获取地址信息
const gettransportinfo = async () => {
    let res = await transportinfo(ruleForm.deliveryTemplateId)
    tableData = res.data.transfees
}
// 获取规格列表
const getspeclist = async () => {
    let res = await speclist()
    console.log(res)
}
getspeclist()
// gettransportinfo()
gettransport()
getcategory()
getListTagList()
Skulistitem()
if (id.value) {
    getInfo()
}
// 获取商品规格
const InputRef = ref<InstanceType<typeof ElInput>>()
// 删除商品规格项
const handleClose = (tag: string, i: any) => {
    skuobj[i].list.splice(skuobj[i].list.indexOf(tag), 1)
}
// 
const showInput = (e: any) => {
    skuobj[e].flag = true
    nextTick(() => {
        InputRef.value!.input!.focus()
    })
}
// 添加商品规格项
const handleInputConfirm = (e: any) => {
    if (inputValue.value) {
        skuobj[e].list.push(inputValue.value)
    }
    skuobj[e].flag = false
    inputValue.value = ''
}

// https://yami-admin-api.yiluxdeng.com/admin/file/upload/element
// 产品状态
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            ruleForm.status === "上架" ? ruleForm.status = 1 : ruleForm.status = 0
            console.log(id)
            if (id.value) {
                onPutshop()
            } else {
                onAddShop()
            }
        } else {
        }
    })
}
// 添加商品
const onAddShop =  () => {
     addshop({
        ...ruleForm,
        skuList: SkuList
    }).then((res) => {
        if(res.status === 200) {
            router.push("/prod/prodList")
        }
    })
    
}
// 编辑商品

const onPutshop =  () => {
     putshop({
        ...ruleForm,
        skuList : SkuList
    }).then((res) => {
        if(res.status === 200) {
            router.push("/prod/prodList")
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>

<style lang="scss" scoped>
.modify {
    width: 100%;
    height: 100%;
    overflow: auto;

    .upload {
        width: 100%;
        display: flex;
        align-items: stretch;

        .img_upload {
            font-size: 14px;
            padding: 10px;
        }

        .images {
            width: 80%;
            display: flex;
            flex-wrap: wrap;
        }
    }
}
</style>